package com.neuedu.yyzx.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.neuedu.yyzx.config.CommonResult;
import com.neuedu.yyzx.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.data.redis.core.RedisTemplate;
import com.neuedu.yyzx.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 第7组....
 * @since 2021-05-21
 */
@RestController

@RequestMapping("/user")
public class UserController {
    @Resource
    BCryptPasswordEncoder encoder;
    @Resource
    IUserService userService;



    @PostMapping("/token")
    CommonResult token(User user) throws JsonProcessingException {

        String token = userService.token(user);
        if (StringUtils.isNotBlank(token)) {
            return CommonResult.success(token);
        } else {
            return CommonResult.failed("用户名或密码不正确");
        }
    }

    @PostMapping("/logout")
    CommonResult logout(HttpServletRequest request) throws JsonProcessingException {
        return CommonResult.success( userService.logout(request));
    }

    @GetMapping("/list")
    CommonResult list(User user) {
        return CommonResult.success(userService.list(user));
    }


    @PostMapping("/add")
    CommonResult add(User user) {
        user.setPassword(encoder.encode(user.getPassword()));
       
        if (userService.add(user))
            return CommonResult.success("ok");
        else
            return CommonResult.failed("用户名已经存在");
    }

    @GetMapping("/getById")
    CommonResult getById(Integer id) {
        return CommonResult.success(userService.getById(id));
    }

    @PostMapping("/update")
    CommonResult update(User user) {
        user.setPassword(encoder.encode(user.getPassword()));
        return CommonResult.success(userService.updateById(user));
    }

    @PostMapping("/del")
    CommonResult del(User user) {
    
        return CommonResult.success(userService.updateById(user));
    }

    @PostMapping("/batchdel")
    CommonResult batchdel(Integer[] ids) {
        return CommonResult.success(userService.batchdel(ids));
    }

    @PostMapping("/back")
    CommonResult back(User user) {
       
        return CommonResult.success(userService.updateById(user));
    }
}
